"""
自定义身份认证后端，来实现多账号登陆
"""
from django.utils import timezone
from django.contrib.auth.backends import ModelBackend
from .models import User

class UsernameMobileAuthBackend(ModelBackend):

    # 重写authenticate实力方法，实现多账号登陆
    # 默认ModelBackend只会根据username过滤用户
    def authenticate(self, request, username=None, password=None, **kwargs):
        # request: 商城站点登陆的时候是一个请求对象；后台管理站点登陆的时候是None
        # username: 用户名或手机号
        # password: 密码

        # 1、根据用户名过滤
        try:
            user = User.objects.get(username=username)
        except User.DoesNotExist as e:
            # 2、根据手机号过滤
            try:
                user = User.objects.get(mobile=username)
            except User.DoesNotExist as e:
                return None


        if request is None:
            # 此次登陆请求，是后台管理站点登陆请求；
            # 验证该用户是否是管理员
            if not user.is_staff:
                return None


        # 3、其中某一个过滤出用户，再校验密码
        if user.check_password(password):
            user.last_login = timezone.localtime() # 记录用户最新登陆的时间
            user.save()
            return user



def my_jwt_response_payload_handler(token, user=None, request=None):
    """
    Returns the response data for both the login and refresh views.
    Override to return a custom response such as including the
    serialized representation of the User.

    Example:

    def jwt_response_payload_handler(token, user=None, request=None):
        return {
            'token': token,
            'user': UserSerializer(user, context={'request': request}).data
        }

    """
    return {
        'username': user.username,
        'user_id': user.id,
        'token': token
    }